<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search mb15">
				<el-button size="default" type="primary" plain class="ml10" @click="onOpenAddRole('add')">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增角色
				</el-button>
			</div>
			<el-table
                :data="state.tableData.data"
                v-loading="state.tableData.loading"
                :border="true"
                :stripe="true"
                :header-cell-style="{backgroundColor: '#f8f8f8', color: '#010101'}"
                style="width: 100%"
            >
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="role_name" label="角色名称" show-overflow-tooltip></el-table-column>
<!--				<el-table-column prop="roleSign" label="角色标识" show-overflow-tooltip></el-table-column>-->
<!--				<el-table-column prop="sort" label="排序" show-overflow-tooltip></el-table-column>-->
<!--				<el-table-column prop="status" label="角色状态" show-overflow-tooltip>-->
<!--					<template #default="scope">-->
<!--						<el-tag type="success" v-if="scope.row.status">启用</el-tag>-->
<!--						<el-tag type="info" v-else>禁用</el-tag>-->
<!--					</template>-->
<!--				</el-table-column>-->
				<el-table-column prop="permission" label="角色权限" show-overflow-tooltip>
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.is_super">拥有所有权限</el-tag>
                        <el-button v-else size="small" type="primary" @click="openEditPermDialog('edit', scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
				<el-table-column prop="remark" label="角色描述" show-overflow-tooltip></el-table-column>
				<el-table-column prop="created_at" label="创建时间" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button :disabled="scope.row.is_super == 1" size="small" text type="primary" @click="onOpenEditRole('edit', scope.row)">修改</el-button>
						<el-button :disabled="scope.row.is_super == 1" size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableData.param.page"
				background
				v-model:page-size="state.tableData.param.page_size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</div>
		<RoleDialog ref="roleDialogRef" @refresh="getTableData()" />
        <el-dialog
            v-model="editPermissionShow"
            title="设置权限"
            width="500"
            :before-close="closePermissionDialog"
        >
            <el-tree
                ref="permissionTree"
                :data="permissionOptions"
                :props="permissionProps"
                :default-expanded-keys="editPermissionForm.permissions"
                :default-checked-keys="editPermissionForm.permissions"
                :check-strictly="true"
                default-expand-all
                check-on-click-node
                show-checkbox
                class="menu-data-tree"
                node-key="id" />

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="editPermissionShow = false">取消</el-button>
                    <el-button type="primary" @click="editPermission">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRole">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import {ElMessageBox, ElMessage, ElTree} from 'element-plus';

import {useRoleApi} from '/@/api/permission/role';
import {useMenuApi} from '/@/api/permission/menu';
const roleApi = useRoleApi();
const menuApi = useMenuApi();

// 引入组件
const RoleDialog = defineAsyncComponent(() => import('/@/views/permission/role/dialog.vue'));

const permissionProps = {
    multiple: true,
    value: 'code',
    label: 'name',
}
const permissionOptions = ref([]);
const editPermissionShow = ref(false);
const editPermissionForm = reactive({ id: 0, permissions: []});
// 定义变量内容
const roleDialogRef = ref();
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
            keyword: '',
			page: 1,
			page_size: 10,
		},
	},
});

// const permissionTree = ref(0);
const permissionTree = ref<InstanceType<typeof ElTree>>()
// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
    roleApi.getRole(state.tableData.param).then((res) => {
        state.tableData.data = res.data.data;
        state.tableData.total = res.data.total;
    }).finally(() => {
        state.tableData.loading = false;
    });

};
// 打开新增角色弹窗
const onOpenAddRole = (type) => {
	roleDialogRef.value.openDialog(type);
};
// 打开修改角色弹窗
const onOpenEditRole = (type, row) => {
	roleDialogRef.value.openDialog(type, row);
};

const openEditPermDialog = (type, row) => {
    editPermissionForm.id = row.id;
    editPermissionShow.value = true;
    editPermissionForm.permissions = [...row.permissions];
    console.log('editPermissionForm.permissions', editPermissionForm.permissions);
};
const editPermission = () => {
    editPermissionForm.permissions = [];
    const Nodes = permissionTree.value.getCheckedNodes(false, true);
    Nodes.map(v => {
        editPermissionForm.permissions.push(v.id);
    });
    roleApi.editPermission(editPermissionForm).then(() => {
        ElMessage.success('设置成功');
        editPermissionShow.value = false;
        getTableData();
    });
};

const closePermissionDialog = () => {
    editPermissionShow.value = false;
}

const getPermissions = () => {
    menuApi.getMenu({}).then((res) => {
        permissionOptions.value = res.data;
    });
};
// 删除角色
const onRowDel = (row) => {
	ElMessageBox.confirm(`此操作将永久删除角色名称：“${row.role_name}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
            roleApi.deleteRole({id: row.id}).then(() => {
                getTableData();
                ElMessage.success('删除成功');
            });
		})
		.catch(() => {});
};
// 分页改变
const onHandleSizeChange = (val) => {
	state.tableData.param.page_size = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val) => {
	state.tableData.param.page = val;
	getTableData();
};
// 页面加载时
onMounted(() => {
	getTableData();
    getPermissions();
});
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
</style>
